<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />

    <!-- 搜索栏 -->
    <van-search
      v-model="key"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <!-- 历史记录 -->
    <van-cell-group v-if="key == ''">
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item, index) in history"
        :key="index"
        :title="item"
        @click="$router.push(`/search/result?key=${item}`)"
      />
    </van-cell-group>

    <!-- 搜索建议 -->
    <van-cell-group v-else>
      <van-cell
        icon="search"
        v-for="(item, index) in colorList"
        :key="index"
        v-show="colorList[0]"
      >
        <div
          v-html="item"
          @click="$router.push(`/search/result?key=${suggestList[index]}`)"
        ></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
//导入发送搜索建议的接口
import { suggestAPI } from '@/api/search'
export default {
  data () {
    return {
      key: "",
      suggestList: [],
      //存历史记录的数组
      history: JSON.parse(localStorage.getItem('history')) || []
    };
  },
  methods: {
    onSearch () {
      //点击搜索的时候
      //非空判断
      if (this.key.trim() == '') return this.$toast('请输入点内容')
      //跳转前先把key拿到存入到历史记录中
      //判断已在数组中没有，没有才存
      if (this.history.indexOf(this.key) == -1) {
        this.history.unshift(this.key),
          //再把数组存到本地存储中
          localStorage.setItem('history', JSON.stringify(this.history))
      }
      //跳转到搜索结果页并传递输入的内容
      this.$router.push(`/search/result?key=${this.key}`)
    },
    async onInput () {
      //非空判断，如果key为空不发送请求
      if (this.key.trim() == "") return this.$toast('请输入搜索关键词')
      // console.log('inputting', this.key)
      const res = await suggestAPI({
        q: this.key
      })
      // console.log(res.data.options)
      this.suggestList = res.data.options
    }
  },
  //根据搜索返回一个加工的数组，数据有依赖，所有用computed
  computed: {
    colorList () {
      return this.suggestList.map(v => {
        //把搜索的关键字找到，并换成带span的效果
        return v?.replace(this.key, `<span style="color:red">${this.key}</span>`)
      })

    }
  }
};
</script>

<style>
</style>